package com.wuseguang.springcloud.service.impl;


import com.wuseguang.springcloud.Classcardservice.ClassCardFieldService;
import com.wuseguang.springcloud.Classcardservice.ClassCardService;
import com.wuseguang.springcloud.Filter.RequestParameterWrapper;
import com.wuseguang.springcloud.dao.jdbc.AttendTwoJdbc;
import com.wuseguang.springcloud.entity.AttendGroup;
import com.wuseguang.springcloud.entity.AttendShift;
import com.wuseguang.springcloud.service.AttendTwoService;
import com.wuseguang.springcloud.service.QuartzClientService;
import com.wuseguang.springcloud.util.CodeUtil;
import com.wuseguang.springcloud.util.DateUtil;
import com.wuseguang.springcloud.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AttendTwoServiceImpl implements AttendTwoService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AttendTwoJdbc attendJdbc;

    @Autowired
    private ClassCardFieldService service;

    //推送接口
    @Autowired
    private ClassCardService classCardService;

    @Autowired
    private QuartzClientService quartzClientService;

    private String flag = "1";
    private Map<String, Object> map;
    private Map<String, Object> stringObjectMap1;





@Override
public void executeInternal() {
        logger.info("执行了SaveAttendTimer2.0V 时间={}", DateUtil.time());

       // String pram = jobExecutionContext.getTrigger().getKey().getGroup();

        String schoolId ="29";//学校id

        String gettime = DateUtil.addDays("2020-10-27", -1);//昨天时间

        int weeksInt = DateUtil.getWeeksInt(gettime);

        String sql = "SELECT id,IF(shift_id!=0,shift_id,(SELECT shift_id FROM attend_group_shift WHERE attend_group_id=attend_group.id AND sort=? ) ) shift_id FROM attend_group WHERE school_id=?";

        List<Map<String, Object>> list = attendJdbc.queryListMap(sql, weeksInt, schoolId);//获取所有考勤组

        String delSql = "delete from class_attendlist  WHERE   attend_group_id=?  AND   DATE(attendtime)= DATE_SUB(CURDATE(),INTERVAL 1 DAY) ";

        String delTwoSql = "delete from class_attendlist  WHERE   attend_group_id=?  AND attendtype is null AND  DATE(attendtime)= DATE_SUB(CURDATE(),INTERVAL 1 DAY) ";

        //休息 缺勤
        String addSql = "INSERT INTO class_attendlist(userid,attend_group_id,shift_id,attendtype,school_id,attendtime,sort,opertime) " +
                "SELECT userid,attend_group_id,?,?,?,'2020-10-26',0,'2020-10-26' FROM attend_group_user WHERE attend_group_id=? ";

        //进班缺卡
        String addTwoSql = "INSERT INTO class_attendlist(userid,attend_group_id,shift_id,attendtype,school_id,attendtime,sort,opertime) " +
                "SELECT a.userid,a.attend_group_id,?,?,?,?,?,'2020-10-26'  FROM attend_group_user a LEFT JOIN class_attendlist l " +
                "ON ( a.attend_group_id=l.attend_group_id AND a.userid=l.userid AND l.attendtime  BETWEEN ? AND ? ) WHERE a.attend_group_id=? AND l.id IS  NULL  GROUP BY a.userid ";

        //缺勤
        String qqSql = "SELECT GROUP_CONCAT(a.userid) string FROM attend_group_user a LEFT JOIN class_attendlist l ON ( a.attend_group_id=l.attend_group_id AND a.userid=l.userid AND l.attendtime  BETWEEN ? AND ? ) WHERE a.attend_group_id=? AND l.id IS  NULL ";


        String sqlShift = "SELECT  `type`, `starttime_one`, `endtime_one`, `starttime_two`, `endtime_two` FROM attend_shift WHERE id=?";

        //String sqlAttendList = "SELECT  a.userid,GROUP_CONCAT(l.attendtime ORDER BY l.attendtime) time,GROUP_CONCAT(l.id ORDER BY l.attendtime) id FROM attend_group_user a LEFT JOIN class_attendlist l ON ( a.attend_group_id=l.attend_group_id AND a.userid=l.userid AND    DATE(l.attendtime)= DATE_SUB(CURDATE(),INTERVAL 1 DAY) ) WHERE a.attend_group_id=?   GROUP BY a.userid  ";

        String updateSql = "UPDATE class_attendlist SET attendtype=?,shift_id=?,sort=? WHERE id IN (SELECT id FROM (SELECT MIN(l.id) id  FROM attend_group_user a LEFT JOIN class_attendlist l  " +
                "ON ( a.attend_group_id=l.attend_group_id AND a.userid=l.userid AND l.attendtime  BETWEEN ? AND ?  ) WHERE a.attend_group_id=?  AND l.id IS NOT NULL GROUP BY a.userid) t )";

        String updateTwoSql = "UPDATE class_attendlist SET attendtype=?,shift_id=?,sort=? WHERE id IN (SELECT id FROM (SELECT a.userid,MAX(l.id) id,GROUP_CONCAT(attendtype) attendtype  FROM attend_group_user a LEFT JOIN class_attendlist l  " +
                " ON ( a.attend_group_id=l.attend_group_id AND a.userid=l.userid AND l.attendtime> ? AND l.attendtime<? ) WHERE a.attend_group_id=? AND l.id IS NOT NULL  GROUP BY a.userid) t WHERE attendtype IS NULL ) ";


        // String userSql = "SELECT t.id string FROM attend_group_user u,student t WHERE  u.userid=t.id AND u.attend_group_id=?";

        String updateGroupSql = "UPDATE attend_group SET shift_id=0 WHERE id=?";

        if (list != null && list.size() > 0) {
            for (Map<String, Object> map : list) {//处理所有考勤组
                Object id = map.get("id");//考勤组id
                String shift_id = map.get("shift_id").toString();
                if ("-1".equals(shift_id) || "0".equals(shift_id)) {//考勤为休息
                    attendJdbc.updateByParameter(delSql, id);
                    attendJdbc.updateByParameter(addSql, 0, 7, schoolId, id);
                } else {//按班次时间处理当前的考勤数据
                    //List<String> userList = attendJdbc.queryListString(userSql, new Object[]{id});
                    Map<String, Object> timeMap = null;
                    try {
                        timeMap = attendJdbc.queryMap(sqlShift, shift_id);
                    } catch (Exception e) {
                        logger.info("executeInternal2.0-->erorr={}", e);
                    }
                    int type = (int) timeMap.get("type");//考勤类型:0 1天1次、1 1天2次
                    String starttimeOne = DateUtil.AddTime(gettime, timeMap.get("starttime_one") + "");
                    String endtimeOne = DateUtil.AddTime(gettime, timeMap.get("endtime_one") + "");
                    String starttimeTwo = DateUtil.AddTime(gettime, timeMap.get("starttime_two") + "");
                    String endtimeTwo = DateUtil.AddTime(gettime, timeMap.get("endtime_two") + "");

                    //考勤类型: 0请假 1进班正常 2进班迟到 3进班缺卡  4离班正常 5离班早退  6离班缺卡 7休息 8缺勤
                    if (type == 0) {
                        String time = "";
                        if (!StringUtils.isEmpty(endtimeOne) && !StringUtils.isEmpty(starttimeTwo)) {//设置了中间休息时段  取中间时间 区分进班迟到 和 离班早退
                            long l = DateUtil.getcompTime(starttimeTwo, endtimeOne);
                            time = DateUtil.addtimeMinutes(endtimeOne, (int) l / 2);
                        } else {//未设置了中间休息时段  取中间时间 区分进班迟到 和 离班早退
                            long l = DateUtil.getcompTime(endtimeTwo, starttimeOne);
                            time = DateUtil.addtimeMinutes(starttimeOne, (int) l / 2);
                        }
                        String userString = attendJdbc.queryString(qqSql, gettime, DateUtil.gettime(), id);

                        attendJdbc.updateByParameter(updateSql, 1, shift_id, 0, gettime, starttimeOne, id);//进班正常
                        //判断是 进班迟到
                        attendJdbc.updateByParameter(updateTwoSql, 2, shift_id, 0, gettime, time, id);
                        attendJdbc.updateByParameter(addTwoSql, shift_id, 3, schoolId, starttimeOne, 0, gettime, time, id);//进班缺卡


                        attendJdbc.updateByParameter(updateSql, 5, shift_id, 1, time, endtimeTwo, id);//离班早退
                        //判断是 离班正常
                        attendJdbc.updateByParameter(updateTwoSql, 4, shift_id, 1, time, DateUtil.gettime(), id);
                        attendJdbc.updateByParameter(addTwoSql, shift_id, 6, schoolId, endtimeTwo, 1, time, DateUtil.gettime(), id);//进班缺卡


                        if (!StringUtils.isEmpty(userString)) {//缺勤
                            String qqAddSql = "INSERT INTO class_attendlist(userid,attend_group_id,shift_id,attendtype,school_id,attendtime,sort,opertime) " +
                                    "   SELECT a.id,?,?,8,?,'2020-10-26',0,'2020-10-26'  FROM student  a WHERE a.id in (" + userString + ")";
                            attendJdbc.updateByParameter(qqAddSql, id, shift_id, schoolId);
                            String delAttendSql = "DELETE FROM  class_attendlist WHERE attend_group_id=?   AND userid IN  (" + userString + ") AND (attendtype=3 or attendtype=6)";
                            attendJdbc.updateByParameter(delAttendSql, id);
                        }
                        attendJdbc.updateByParameter(delTwoSql, id);//删除null的
                        attendJdbc.updateByParameter(updateGroupSql, id);//修改考勤组
                    } else {
                        //求第一段考勤的中间时间  用来区分 进班迟到和离班早退
                        long l = DateUtil.getcompTime(endtimeOne, starttimeOne);
                        String s = DateUtil.addtimeMinutes(starttimeOne, (int) l / 2);
                        //求第一段考勤的结束时间和第二段开始时间的中间时间  用来区分 离班正常和第二段的进班正常
                        long l1 = DateUtil.getcompTime(starttimeTwo, endtimeOne);
                        String s1 = DateUtil.addtimeMinutes(endtimeOne, (int) l1 / 2);
                        //求第二段考勤的中间时间  用来区分 进班迟到和离班早退
                        long l2 = DateUtil.getcompTime(endtimeTwo, starttimeTwo);
                        String s3 = DateUtil.addtimeMinutes(starttimeTwo, (int) l2 / 2);

                        String userString = attendJdbc.queryString(qqSql, gettime, DateUtil.gettime(), id);

                        attendJdbc.updateByParameter(updateSql, 1, shift_id, 0, gettime, starttimeOne, id);//进班正常
                        //判断是 进班迟到
                        attendJdbc.updateByParameter(updateTwoSql, 2, shift_id, 0, gettime, s, id);
                        attendJdbc.updateByParameter(addTwoSql, shift_id, 3, schoolId, starttimeOne, 0, gettime, s, id);//进班缺卡


                        attendJdbc.updateByParameter(updateSql, 5, shift_id, 1, s, endtimeOne, id);//离班早退
                        //判断是 离班正常
                        attendJdbc.updateByParameter(updateTwoSql, 4, shift_id, 1, s, s1, id);
                        attendJdbc.updateByParameter(addTwoSql, shift_id, 6, schoolId, endtimeOne, 1, s, s1, id);//离班缺卡


                        //考勤类型: 0请假 1进班正常 2进班迟到 3进班缺卡  4离班正常 5离班早退  6离班缺卡 7休息 8缺勤
                        //第二段
                        attendJdbc.updateByParameter(updateSql, 1, shift_id, 2, s1, starttimeTwo, id);//进班正常
                        //判断是 进班迟到
                        attendJdbc.updateByParameter(updateTwoSql, 2, shift_id, 2, s1, s3, id);
                        attendJdbc.updateByParameter(addTwoSql, shift_id, 3, schoolId, starttimeTwo, 2, s1, s3, id);//进班缺卡


                        //第二段
                        attendJdbc.updateByParameter(updateSql, 5, shift_id, 3, s3, endtimeTwo, id);//离班早退
                        //判断是 离班正常
                        attendJdbc.updateByParameter(updateTwoSql, 4, shift_id, 3, s3, DateUtil.gettime(), id);
                        attendJdbc.updateByParameter(addTwoSql, shift_id, 6, schoolId, endtimeTwo, 3, s3, DateUtil.gettime(), id);//离班缺卡

                        if (!StringUtils.isEmpty(userString)) {//缺勤
                            String qqAddSql = "INSERT INTO class_attendlist(userid,attend_group_id,shift_id,attendtype,school_id,attendtime,sort,opertime) " +
                                    "   SELECT a.id,?,?,8,?,'2020-10-26',0,'2020-10-26'  FROM student  a WHERE a.id in (" + userString + ")";
                            attendJdbc.updateByParameter(qqAddSql, id, shift_id, schoolId);
                            String delAttendSql = "DELETE FROM  class_attendlist WHERE attend_group_id=?   AND userid IN  (" + userString + ") AND (attendtype=3 or attendtype=6)";
                            attendJdbc.updateByParameter(delAttendSql, id);
                        }

                        attendJdbc.updateByParameter(delTwoSql, id);//删除null的
                        attendJdbc.updateByParameter(updateGroupSql, id);//修改考勤组
                    }
                }
            }
        }
    }









    /**
     * 查询所有班次列表
     *
     * @Description:
     * @Param: [school_id] 学校id
     * @return: java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @Author: zm
     * @Date: 2020/8/3
     */
    @Override
    public List<Map<String, Object>> queryAttendShiftAll(String school_id) {
        String sql = "SELECT  id,name,type,IF(TYPE=0, CONCAT(starttime_one,'-',endtime_two,IF(endtime_one  IS NULL,'',CONCAT('  中午休息时间: ',endtime_one,'-',starttime_two))),CONCAT(starttime_one,'-',endtime_one,',',starttime_two,'-',endtime_two))  time , " +
                "  starttime_one starttime,endtime_one endtime,starttime_two starttime1,endtime_two  endtime1,s_ejecttime_one s_ejecttime,e_ejecttime_one e_ejecttime,s_ejecttime_two s_ejecttime1," +
                " e_ejecttime_two e_ejecttime1,school_id FROM attend_shift WHERE school_id=? AND state=0";
        return attendJdbc.queryListMap(sql, school_id);
    }

    /**
     * @描述 根据id 查班次详情
     * @创建人 zm
     * @创建时间 2020/2/5
     */
    @Override
    public Map<String, Object> queryAttendShiftById(String school_id, Integer id) {
        String sql = " SELECT  id,name,type,starttime_one starttime,endtime_one endtime,starttime_two starttime1,endtime_two endtime1,s_ejecttime_one s_ejecttime,e_ejecttime_one e_ejecttime,s_ejecttime_two s_ejecttime1,e_ejecttime_two e_ejecttime1,school_id FROM attend_shift WHERE id=? AND school_id= ?  and state=0";
        Map<String, Object> map = null;
        try {
            map = attendJdbc.queryMap(sql, id, school_id);
        } catch (Exception e) {
            logger.info("queryAttendShiftById-->map,error={}", e);
        }
        return map;
    }


    /**
     * @描述 修改班次
     * @创建人 zm
     * @创建时间 2020/2/5
     */
    @Override
    @Transactional
    public Result updateAttendShiftById(String school_id, AttendShift attendShift) {
        int weeksInt = DateUtil.getWeeksInt(DateUtil.gettime());//获取当天对应的班次索引
        String sql = "SELECT attend_group_id  FROM  attend_group_shift WHERE shift_id=? AND sort=?";//判断当天使用的班次是否有修改的班次
        List<String> integers = attendJdbc.queryListString(sql, new Object[]{attendShift.getId(), weeksInt});
        String s = "";
        //判断是否明日生效
        if (integers != null && integers.size() > 0) {
            String join = String.join(",", integers);
            sql = "SELECT  GROUP_CONCAT(class_id)  string FROM class_attend_group WHERE attend_group_id IN (" + join + ")";
            s = attendJdbc.queryString(sql);//获取考勤组所有有关联的班级id
            if (attendShift.getState() == 1) {// 0立即生效 1明天生效//添加一个备份考勤班次,用于当天使用
                sql = "INSERT INTO `attend_shift` (`name`, `type`, `starttime_one`, `endtime_one`, `s_ejecttime_one`, `e_ejecttime_one`, `starttime_two`, `endtime_two`, `s_ejecttime_two`, `e_ejecttime_two`, `school_id`, `opertime`,`state`) " +
                        "SELECT `name`, `type`, `starttime_one`, `endtime_one`, `s_ejecttime_one`, `e_ejecttime_one`, `starttime_two`, `endtime_two`, `s_ejecttime_two`, `e_ejecttime_two`, `school_id`, NOW(),1 FROM attend_shift WHERE id=? ";
                Long aLong = attendJdbc.updateByParameterGetId(sql, attendShift.getId());
                sql = "UPDATE attend_group SET shift_id=? WHERE id IN (" + join + ")";
                attendJdbc.updateByParameter(sql, aLong);
            } else {// 0立即生效
                sql = "UPDATE attend_group SET shift_id=? WHERE id IN (" + join + ")";
                attendJdbc.updateByParameter(sql, 0);
            }
            service.classesAndCardsMultiple(s, "dialogflag", "2");
        }
        //修改班次
        sql = "update `attend_shift` set `name`=?, `type`=?, `starttime_one`=?, `endtime_one`=?, `s_ejecttime_one`=?, `e_ejecttime_one`=?, `starttime_two`=?, `endtime_two`=?, `s_ejecttime_two`=?, `e_ejecttime_two`=?,  `opertime`=now() where id=?";
        int i = attendJdbc.updateByParameter(sql, attendShift.getName(), attendShift.getType(), attendShift.getStarttime(), attendShift.getEndtime(),
                attendShift.getS_ejecttime(), attendShift.getE_ejecttime(), attendShift.getStarttime1(),
                attendShift.getEndtime1(), attendShift.getS_ejecttime1(), attendShift.getE_ejecttime1(), attendShift.getId());
        if (i > 0) {
            if (!StringUtils.isEmpty(s)) {
                classCardService.classesAndCards(s);
            }
            return new Result();
        }
        return new Result(CodeUtil.MODIFICATION_FAILED);
    }


    /**
     * @描述 添加班次
     * @创建人 zm
     * @创建时间 2020/2/5
     */
    @Override
    public Result addAttendShiftById(String school_id, AttendShift attendShift) {
        String sql = "SELECT count(1) ints FROM attend_shift WHERE school_id=? AND name=? AND state=0";
        if (attendJdbc.queryInteger(sql, school_id, attendShift.getName()) > 0) {
            return new Result(CodeUtil.DUPLICATE_ACCOUNT_SHIFT);
        }
        sql = "insert into `attend_shift` (`name`, `type`, `starttime_one`, `endtime_one`, `s_ejecttime_one`, `e_ejecttime_one`, `starttime_two`, `endtime_two`, `s_ejecttime_two`, `e_ejecttime_two`, `school_id`, `opertime`) values(?,?,?,?,?,?,?,?,?,?,?,now())";
        int i = attendJdbc.updateByParameter(sql, attendShift.getName(), attendShift.getType(), attendShift.getStarttime(), attendShift.getEndtime(),
                attendShift.getS_ejecttime(), attendShift.getE_ejecttime(), attendShift.getStarttime1(),
                attendShift.getEndtime1(), attendShift.getS_ejecttime1(), attendShift.getE_ejecttime1(), school_id);
        if (i > 0) {
            return new Result();
        }
        return new Result(CodeUtil.ADD_FAILURE);
    }


    /**
     * @描述 删除班次
     * @创建人 zm
     * @创建时间 2020/2/5
     */
    @Override
    @Transactional
    public Result delAttendShiftById(String school_id, Integer id) {
        String sql = "SELECT COUNT(1) ints FROM  attend_group_shift WHERE shift_id=? ";
        if (attendJdbc.queryInteger(sql, id) > 0) {
            return new Result(CodeUtil.CANNOT_DELETE);
        }
        sql = "update  attend_shift set state=1  WHERE id=? AND  school_id=? ";
        int i = attendJdbc.updateByParameter(sql, id, school_id);
        if (i > 0) {
            return new Result();
        }
        return new Result(CodeUtil.DELETE_FAILED);
    }


    @Override
    public List<Map<String, Object>> queryAttendGroupAll(String school_id, String name) {
        StringBuilder stringBuilder = new StringBuilder(" SELECT g.id,g.name,(SELECT COUNT(1) FROM attend_group_user a,student t WHERE  a.userid=t.id and  a.attend_group_id=g.id) count,(SELECT COUNT(1) FROM class_attend_group a,classes s WHERE a.class_id=s.id and a.attend_group_id=g.id) classcount,g.attend_type attendtype,g.attend_group_type type,g.shift_id FROM attend_group g WHERE g.school_id=? ");
        if (!StringUtils.isEmpty(name)) {
            stringBuilder.append("and g.name like ").append("'%").append(name).append("%'");
        }
        List<Map<String, Object>> mapList = attendJdbc.queryListMap(stringBuilder.toString(), school_id);
        String sql = " SELECT  IFNULL(CONCAT((CASE t.sort WHEN 6 THEN '周日' WHEN 0 THEN '周一' WHEN 1 THEN '周二' WHEN 2 THEN '周三' WHEN 3 THEN '周四' WHEN 4 THEN '周五' WHEN 5 THEN '周六' END),': ',IF(TYPE=0, CONCAT(starttime_one,'-',endtime_two,  " +
                " IF(endtime_one  IS NULL,'',CONCAT('  中午休息时间: ',endtime_one,'-',starttime_two))),CONCAT(starttime_one,'-',endtime_one,',',starttime_two,'-',endtime_two))),CONCAT((CASE t.sort WHEN 6 THEN '周日' WHEN 0 THEN '周一' WHEN 1 THEN '周二' WHEN 2 THEN '周三' WHEN 3 THEN '周四' WHEN 4 THEN '周五' WHEN 5 THEN '周六' END),': ','休息')) " +
                " time FROM attend_group_shift t LEFT JOIN  attend_shift a ON (t.shift_id=a.id ) WHERE t.attend_group_id=? ORDER BY t.sort ";
        for (int i = 0; i < mapList.size(); i++) {//封装考勤数据
            Map<String, Object> stringObjectMap = mapList.get(i);
            Object id = stringObjectMap.get("id");
            List<String> strings = attendJdbc.queryListString(sql, new Object[]{id});
            stringObjectMap.put("list", strings);
        }
        return mapList;
    }

    /**
     * @描述 查该学校所有考勤组
     * @创建人 zm
     * @创建时间 2020/2/5
     */
    @Override
    public List<Map<String, Object>> queryAttendGroup(String school_id, String admin, String teacherId) {
        String sql = "SELECT id,name,attend_group_type type FROM attend_group WHERE school_id=? ";
        if (!"0".equals(admin)) {
            String classIds = attendJdbc.findClassIds(school_id, teacherId);
            sql = " SELECT a.id,a.name,a.attend_group_type type  FROM attend_group a,class_attend_group g WHERE a.id=g.attend_group_id AND a.school_id=? AND  g.class_id in (" + classIds + ")";
        }
        List<Map<String, Object>> mapList = attendJdbc.queryListMap(sql, school_id);
        return mapList;
    }

    /**
     * 根据考勤组id查询对应年级/班级信息
     *
     * @Description:
     * @Param:
     * @return:
     * @Author: zm
     * @Date: 2020/8/3
     */
    @Override
    public List<Map<String, Object>> queryAttendGroupClass(Integer id) {
        String sql = "SELECT  g.id,g.name FROM class_attend_group c, grade g,classes s WHERE c.attend_group_id=? AND c.class_id=s.id AND g.id=s.grade_id GROUP BY g.id";
        List<Map<String, Object>> mapList = attendJdbc.queryListMap(sql, id);
        sql = "SELECT  s.id,s.name FROM class_attend_group c, grade g,classes s WHERE c.attend_group_id=? AND g.id=? AND c.class_id=s.id AND g.id=s.grade_id ";
        for (int i = 0; i < mapList.size(); i++) {
            Map<String, Object> stringObjectMap = mapList.get(i);
            Object id1 = stringObjectMap.get("id");
            stringObjectMap.put("list", attendJdbc.queryListMap(sql, id, id1));
        }
        return mapList;
    }

    /**
     * @描述 根据考勤组查班级
     * @创建人 zm
     * @创建时间 2020/3/6
     */
    @Override
    public String attendGroupClassid(Integer id, String s) {
        String sql2 = "SELECT GROUP_CONCAT(class_id) string FROM class_attend_group   WHERE attend_group_id=?";
        String sql = " UPDATE bancard SET dialogflag=? WHERE classroomid IN ( SELECT id FROM classroom WHERE classid IN (SELECT class_id FROM class_attend_group  WHERE attend_group_id=?)) ";
        attendJdbc.updateByParameter(sql, 2, id);
        if (!StringUtils.isEmpty(s)) {
            attendJdbc.updateByParameter(sql, 0, id);
        }
        return attendJdbc.queryString(sql2, id);
    }


    /**
     * @Description: 删除考勤组
     * @Param: [request, id]
     * @return: com.wuseguang.springcloud.util.Result
     * @Author: zm
     * @Date: 2020/8/3
     */
    @Override
    @Transactional
    public int delAttendGroupById(String school_id, Integer id) {
        //String s = attendGroupClassid(id);
        String sql = " DELETE FROM attend_group  WHERE id=? AND  school_id=?";
        int i = attendJdbc.updateByParameter(sql, id, school_id);
       /* if (i > 0) {
            String sql1 = " DELETE FROM class_attend_group   WHERE attend_group_id=? ";
            attendJdbc.updateByParameter(sql1, id);
           if (!StringUtils.isEmpty(s)) {
                service.pushClassCard(s, "dialogflag", flag);
            }
        }*/
        return i;
    }

    /**
     * @描述 根据id查询考勤组详细内容
     * @创建人 zm
     * @创建时间 2020/2/5
     */
    @Override
    public Map<String, Object> queryAttendGroupById(String school_id, Integer id) {
        String sql = " SELECT g.id,g.name,(SELECT COUNT(1) FROM attend_group_user a,student t WHERE  a.userid=t.id and  a.attend_group_id=g.id) count,(SELECT COUNT(1) FROM class_attend_group a,classes s WHERE a.class_id=s.id and a.attend_group_id=g.id) classcount,g.attend_type attendtype,g.attend_group_type type,(SELECT GROUP_CONCAT(shift_id ORDER BY sort) FROM attend_group_shift WHERE attend_group_id=g.id ) shift_id FROM attend_group g WHERE g.school_id=? and g.id=?";
        Map<String, Object> mapList = attendJdbc.queryMap(sql, school_id, id);
        sql = "SELECT  IF(IF(TYPE=0, CONCAT(starttime_one,'-',endtime_two, IF(endtime_one  IS NULL,'',CONCAT(' 中午休息时间: ',endtime_one,'-',starttime_two))), " +
                " CONCAT(starttime_one,'-',endtime_one,',',starttime_two,'-',endtime_two))IS NULL,'休息', IF(TYPE=0, CONCAT(starttime_one,'-',endtime_two, IF(endtime_one  IS NULL,'',  " +
                " CONCAT(' 中午休息时间: ',endtime_one,'-',starttime_two))),CONCAT(starttime_one,'-',endtime_one,',',  starttime_two,'-',endtime_two)))  TIME FROM attend_group_shift t LEFT JOIN attend_shift a ON (t.shift_id=a.id ) WHERE t.attend_group_id=? ORDER BY t.sort";
        List<String> strings = attendJdbc.queryListString(sql, new Object[]{id});
        mapList.put("shiftlist", strings);
        return mapList;
    }

    /**
     * @描述 修改考勤组
     * @创建人 zm
     * @创建时间 2020/2/5
     */
    @Override
    @Transactional
    public int updateAttendGroup(String school_id, AttendGroup attendGroup) {
        int i = 0;
        Integer attend_groupid = attendGroup.getId();//考勤组id
        String userids = attendGroup.getUserids();//考勤人员id
        String classids = attendGroup.getClassids();//考情班级id
        String shift_id = attendGroup.getShift_id();//应用的班次id
        Integer state = attendGroup.getState();//0立即生效 1明天生效
        if (!StringUtils.isEmpty(userids) && attend_groupid != null) {//修改了考勤组信息
            String sql = "INSERT INTO attend_group_user(userid,attend_group_id,opertime) VALUES(?,?,NOW())";
            i += attendJdbc.updateAttendGroupUser(sql, userids, attend_groupid);
            logger.info("updateAttendGroupUser-->i={}", i);
        }

        if (!StringUtils.isEmpty(classids) && attend_groupid != null) {//修改了班级
            String sql = "INSERT INTO class_attend_group(class_id,attend_group_id,opertime) VALUES(?,?,NOW())";
            i += attendJdbc.updateAttendGroupClass(sql, classids, attend_groupid);
            logger.info("updateAttendGroupClass-->i={}", i);
        }
        if (!StringUtils.isEmpty(classids)) {//修改字段心跳
            service.classesAndCardsMultiple(classids, "dialogflag", "2");
        }

        int weeksInt = DateUtil.getWeeksInt(DateUtil.gettime());
        String sql = "SELECT shift_id string FROM  attend_group_shift WHERE attend_group_id=? AND sort=?";//判断当天使用的班次是否有修改的班次
        String s = attendJdbc.queryString(sql, new Object[]{attend_groupid, weeksInt});
        if (shift_id != null && s.equals(shift_id.split(",")[weeksInt])) {//如果相等说明当天使用的班次没有发生改变
            saveAttendGroupShift(shift_id, attend_groupid);
            i += saveAttendGroup(attendGroup.getName(), 0, school_id, attend_groupid);
            return i;
        }

        if (state == 1) {//明天生效
            Long aLong = -1L;
            if (!"0".equals(s)) {
                sql = "INSERT INTO `attend_shift` (`name`, `type`, `starttime_one`, `endtime_one`, `s_ejecttime_one`, `e_ejecttime_one`, `starttime_two`, `endtime_two`, `s_ejecttime_two`, `e_ejecttime_two`, `school_id`, `state`, `opertime`)  SELECT `name`, `type`, `starttime_one`, `endtime_one`, `s_ejecttime_one`, `e_ejecttime_one`, `starttime_two`, `endtime_two`, `s_ejecttime_two`, `e_ejecttime_two`, `school_id`,1,NOW()  FROM attend_shift WHERE id=?";
                aLong = attendJdbc.updateByParameterGetId(sql, s);
            }
            i += saveAttendGroup(attendGroup.getName(), aLong, school_id, attend_groupid);
            saveAttendGroupShift(shift_id, attend_groupid);
            return i;
        }
        //service.classesAndCardsMultiple(classids, "dialogflag", "2");
        i += saveAttendGroup(attendGroup.getName(), 0, school_id, attend_groupid);//立即生效
        saveAttendGroupShift(shift_id, attend_groupid);
        return i;
    }


    @Override
    public Map<String, Object> downloadAttend(RequestParameterWrapper request, HttpServletResponse response, String sid, String attend_groupid, String starttime, String endtime, String classids) {
        String schoolId = request.getParam("schoolId");
        logger.info("downloadAttend-->,attend_groupid={}, schoolId={}, starttime={}, endtime={}, userids={}, sid={}", attend_groupid, schoolId, starttime, endtime, classids, sid);
        return queryAttendAll(attend_groupid, schoolId, starttime, endtime, classids);
    }


    /**
     * @描述 添加考勤组
     * @创建人 zm
     * @创建时间 2020/2/5
     */
    @Override
    @Transactional
    public int addAttendGroup(String school_id, AttendGroup attendGroup) {
        String sql = "insert into `attend_group` (`name`, `attend_type`, `attend_group_type`, `school_id`, `opertime`) values(?,?,?,?,now())";
        Integer aLong = attendJdbc.updateByParameterGetId(sql, attendGroup.getName(), attendGroup.getType(), attendGroup.getAttend_group_type(), school_id).intValue();
        if (aLong > 0) {
            String userids = attendGroup.getUserids();//考勤人员id
            String classids = attendGroup.getClassids();//考情班级id
            String shift_id = attendGroup.getShift_id();//应用的班次id

            if (!StringUtils.isEmpty(userids)) {//修改了考勤组信息
                sql = "INSERT INTO attend_group_user(userid,attend_group_id,opertime) VALUES(?,?,NOW())";
                attendJdbc.updateAttendGroupUser(sql, userids, aLong);
                service.classesAndCardsMultiple(classids, "dialogflag", "2");
            }

            if (!StringUtils.isEmpty(classids)) {//修改了班级
                sql = "INSERT INTO class_attend_group(class_id,attend_group_id,opertime) VALUES(?,?,NOW())";
                attendJdbc.updateAttendGroupClass(sql, classids, aLong);
                service.classesAndCardsMultiple(classids, "dialogflag", "1");
            }

            if (!StringUtils.isEmpty(shift_id)) {//修改考勤组和班次
                saveAttendGroupShift(shift_id, aLong);
            }
        }
        try {
            quartzClientService.saveAttend();
        } catch (Exception e) {

        }
        return aLong;
    }

    /**
     * @描述 组合查询学生或教师考勤
     * @创建人 zm
     * @创建时间 2020/2/3
     */
    @Override//考勤类型: 0请假 1进班正常 2进班迟到 3进班缺卡  4离班正常 5离班早退  6离班缺卡 7休息 8缺勤
    public Map<String, Object> queryAttendAll(String attend_groupid, String school_id, String starttime, String endtime, String classids) {
        long startTime = System.currentTimeMillis(); //获取开始时间

        String gettime = DateUtil.time();
        if (DateUtil.getDay(gettime, endtime) > 0) {//结束时间大于当前时间，取当前时间
            endtime = gettime;
        }
        if (DateUtil.getDay(gettime, starttime) > 0) {//开始时间大于当前时间，去当前时间
            starttime = gettime;
        }
        HashMap<String, Object> listMap = new HashMap<>();
        String sql = " SELECT t.id,t.student_name name,s.name cname,(select IFNULL(SUM(if(attendtype=1 || attendtype=4,1,0)),0) from class_attendlist where  userid=t.id  and opertime BETWEEN ? and ? )  zccount,(select IFNULL(SUM(if(attendtype=8,1,0)),0) from class_attendlist where  userid=t.id  and opertime BETWEEN ? and ? )  qqcount ,(select IFNULL(SUM(if(attendtype=3 || attendtype=6,1,0)),0) from class_attendlist where  userid=t.id  and opertime BETWEEN ? and ? )  qkcount ,(select IFNULL(SUM(if(attendtype=2,1,0)),0) from class_attendlist where  userid=t.id  and opertime BETWEEN ? and ? )  zdcount,(select IFNULL(SUM(if(attendtype=5,1,0)),0) from class_attendlist where  userid=t.id  and opertime BETWEEN ? and ? )  ztcount FROM (attend_group_user u,student t) LEFT JOIN classes s on (t.class_id=s.id) WHERE u.userid=t.id AND u.attend_group_id=?";
        if (!StringUtils.isEmpty(classids)) {//按班级筛选
            sql += " AND t.class_id in (" + classids + ") ";
        }
        List<Map<String, Object>> maps = attendJdbc.queryListMap(sql, starttime, endtime, starttime, endtime, starttime, endtime, starttime, endtime, starttime, endtime, attend_groupid);
        sql = "SELECT  GROUP_CONCAT((CASE t.attendtype WHEN 0  THEN '请假' WHEN 1 THEN '进班正常' WHEN 2 THEN '进班迟到' WHEN 3 THEN '进班缺卡 ' WHEN 4 THEN '离班正常' WHEN 5 THEN '离班早退' WHEN 6 THEN '离班缺卡' WHEN 7 THEN '休息' WHEN 8 THEN '缺勤' END) ORDER BY sort " +
                " SEPARATOR ' ' ) attend,CONCAT(t.opertime,'&',t.userid) userid FROM class_attendlist t WHERE   t.attend_group_id=?   AND   t.opertime BETWEEN ?  AND ? GROUP BY t.opertime, t.userid";
        Map<String, String> map = attendJdbc.queryAttendListMap(sql, attend_groupid, starttime, endtime);

        List<String> weekList = new ArrayList<String>();
        long wdays = DateUtil.getDay(starttime, endtime);
        weekList.add("姓名");
        weekList.add("部门");
        weekList.add("正常次数");
        weekList.add("缺勤次数");
        weekList.add("缺卡次数");
        weekList.add("迟到次数");
        weekList.add("早退次数");
        for (int i = 0; i <= wdays; i++) {
            String s2 = DateUtil.addDays(starttime, i);
            weekList.add(new StringBuilder(s2).append("(").append(DateUtil.getWeeks(s2)).append(")").toString());
        }

        int aType = 0;//0 不包含当天考勤  1包含当天考勤

        Map<String, String> stringMap = null;
        Map<String, Object> timeMap = null;

        int type = -1;//0 一段考勤 1二段考勤
        String starttimeOne = "";//第一段开始时间
        String endtimeOne = "";
        String starttimeTwo = "";
        String endtimeTwo = "";

        if (DateUtil.getDay(gettime, endtime) == 0 && DateUtil.getDay(gettime, starttime) != 0) {//当天考勤数据 动态处理
            try {
                aType = 1;
                sql = "SELECT  a.userid,GROUP_CONCAT(a.attendtime ORDER BY a.attendtime) attend FROM class_attendlist a,student t WHERE a.userid =t.id ";
                if (!StringUtils.isEmpty(classids)) {//按班级筛选
                    sql += " AND t.class_id in (" + classids + ") ";
                }
                sql += " AND attend_group_id=? AND TO_DAYS(attendtime)=TO_DAYS(NOW()) GROUP BY userid ";
                stringMap = attendJdbc.queryAttendListMap(sql, attend_groupid);//当天的所有考勤数据

                sql = "  SELECT g.shift_id  , g.id , g.name ,g.attend_type grouptype ,g.attend_group_type,f.id shiftid,f.type,f.starttime_one starttime,f.endtime_one endtime,f.starttime_two starttime1,f.endtime_two endtime1 " +
                        " ,f.s_ejecttime_one  s_ejecttime,f.e_ejecttime_one e_ejecttime,f.s_ejecttime_two s_ejecttime1,f.e_ejecttime_two e_ejecttime1,f.school_id FROM  " +
                        "     attend_group g,attend_shift f WHERE g.id=? AND f.id=g.shift_id  ORDER BY f.starttime_one  LIMIT 1 ";
                try {
                    timeMap = attendJdbc.queryMap(sql, attend_groupid);
                } catch (Exception e) {
                    logger.info("queryAttend 考勤没有次日生效-->erorr={}", e);
                }

                if (timeMap == null) {
                    ///情况二 当天考勤  当天生效
                    sql = " SELECT  g.shift_id , g.id , g.name ,g.attend_group_type,f.id shiftid,f.type,f.starttime_one starttime,f.endtime_one endtime,f.starttime_two starttime1,f.endtime_two endtime1 ,f.s_ejecttime_one  s_ejecttime,f.e_ejecttime_one e_ejecttime,f.s_ejecttime_two s_ejecttime1,f.e_ejecttime_two e_ejecttime1,f.school_id FROM   attend_group g,attend_shift f,attend_group_shift t WHERE  g.id=?  AND t.shift_id=f.id AND t.attend_group_id=g.id  AND t.sort=? ORDER BY f.starttime_one  limit 1";
                    try {
                        timeMap = attendJdbc.queryMap(sql, attend_groupid, DateUtil.getWeeksInt(gettime));
                    } catch (Exception e) {
                        logger.info("queryAttendUserStatusAll-->erorr={}", e);
                    }
                }
                if (timeMap != null) {
                    type = (int) timeMap.get("type");//考勤类型:0 1天1次、1 1天2次
                    starttimeOne = DateUtil.AddTime(gettime, timeMap.get("starttime") + "");

                    endtimeOne = DateUtil.AddTime(gettime, timeMap.get("endtime") + "");
                    starttimeTwo = DateUtil.AddTime(gettime, timeMap.get("starttime1") + "");

                    endtimeTwo = DateUtil.AddTime(gettime, timeMap.get("endtime1") + "");
                }
            } catch (Exception e) {
                logger.info("获取班次考勤时间异常。。。。。。");
            }

        }


        int size = maps.size();
        for (int j = 0; j < size; j++) {//遍历考勤人员
            int zc = 0;//当天 正常次数
            int qk = 0;//当天 缺卡次数
            int cd = 0;//当天 迟到次数
            int zt = 0;//当天 早退次数


            int a = 0;//"进班缺卡"
            int b = 0;//"进班迟到"
            int c = 0;//"离班缺卡"
            int d = 0;//"离班早退"
            int e = 0;//"进班正常"
            int f = 0;//"离班正常"


            int A = 0;//"进班缺卡"
            int B = 0;//"进班迟到"
            int C = 0;//"离班缺卡"
            int D = 0;//"离班早退"
            int E = 0;//"进班正常
            int F = 0;//"离班正常


            List<String> list = new ArrayList<>();
            Map<String, Object> stringObjectMap = maps.get(j);
            Object id = stringObjectMap.get("id");
            String s2 = "&" + id;

            if (aType == 0) {//0 不包含当天考勤  1包含当天考勤
                for (int i = 0; i <= wdays; i++) {//遍历查询时间周期
                    String s = DateUtil.addDays(starttime, i);
                    String s1 = map.get(s + s2);
                    list.add(s1);
                }
            }
            if (aType == 1) {//0 不包含当天考勤  1包含当天考勤
                for (int i = 0; i <= wdays - 1; i++) {//遍历查询时间周期
                    String s = DateUtil.addDays(starttime, i);
                    String s1 = map.get(s + s2);
                    list.add(s1);
                }
                if (timeMap == null) {//查不到时 为休息
                    list.add("休息");
                } else {
                    String attendString = "未打卡";

                    if (type == 0) {
                        String time = "";
                        if (!StringUtils.isEmpty(endtimeOne) && !StringUtils.isEmpty(starttimeTwo)) {//设置了中间休息时段  取中间时间 区分进班迟到 和 离班早退
                            long l = DateUtil.getcompTime(starttimeTwo, endtimeOne);
                            time = DateUtil.addtimeMinutes(endtimeOne, (int) l / 2);
                        } else {//未设置了中间休息时段  取中间时间 区分进班迟到 和 离班早退
                            long l = DateUtil.getcompTime(endtimeTwo, starttimeOne);
                            time = DateUtil.addtimeMinutes(starttimeOne, (int) l / 2);
                        }

                        if (stringMap == null || stringMap.get(id + "") == null) {//今天没有考勤
                            if (DateUtil.valueCompTime(DateUtil.time(), time) > 0) {
                                attendString = "进班缺卡";
                                qk++;
                            }
                        }
                        if (stringMap != null && stringMap.get(id + "") != null) {
                            String s = stringMap.get(id + "");
                            String[] split = s.split(",");
                            for (int i = 0; i < split.length; i++) {
                                String attendtime = split[i];
                                if (DateUtil.valueCompTime(time, attendtime) >= 0) {//第一段考勤是否有考勤
                                    if (DateUtil.valueCompTime(starttimeOne, attendtime) >= 0) {
                                        e = 1;//"进班正常"
                                    }
                                    if (DateUtil.valueCompTime(time, attendtime) > 0) {//"进班迟到"
                                        if (e == 0) {
                                            b = 1;
                                        }
                                    }
                                }
                                if (DateUtil.valueCompTime(time, attendtime) <= 0 && DateUtil.valueCompTime(endtimeTwo, attendtime) >= 0) {//"离班早退"
                                    if (f == 0) {
                                        d = 1;
                                    }
                                }
                                if (DateUtil.valueCompTime(endtimeTwo, attendtime) < 0) {//"离班正常"
                                    if (d == 0) {
                                        f = 1;
                                    }
                                }
                            }
                            if (e == 0 && b == 0) {
                                a = 1;
                                qk = 1;//"缺卡"
                            }
                            attendString = attendString(a, b, c, d, e, f, A, B, C, D, E, F);
                        }
                    } else {
                        //求第一段考勤的中间时间  用来区分 进班迟到和离班早退
                        long l = DateUtil.getcompTime(endtimeOne, starttimeOne);
                        String s = DateUtil.addtimeMinutes(starttimeOne, (int) l / 2);
                        //求第一段考勤的结束时间和第二段开始时间的中间时间  用来区分 离班正常和第二段的进班正常
                        long l1 = DateUtil.getcompTime(starttimeTwo, endtimeOne);
                        String s1 = DateUtil.addtimeMinutes(endtimeOne, (int) l1 / 2);
                        //求第二段考勤的中间时间  用来区分 进班迟到和离班早退
                        long l2 = DateUtil.getcompTime(endtimeTwo, starttimeTwo);
                        String s3 = DateUtil.addtimeMinutes(starttimeTwo, (int) l2 / 2);
                        if (stringMap == null || stringMap.get(id + "") == null) {//今天没有考勤
                            if (DateUtil.valueCompTime(DateUtil.time(), s) > 0) {
                                attendString = "进班缺卡";
                                qk++;
                            }

                            if (DateUtil.valueCompTime(DateUtil.time(), s1) > 0) {
                                attendString = "进班缺卡 离班缺卡";
                                qk++;
                            }

                            if (DateUtil.valueCompTime(DateUtil.time(), s3) > 0) {
                                attendString = "进班缺卡 离班缺卡 进班缺卡";
                                qk++;
                            }
                        }
                        if (stringMap != null && stringMap.get(id + "") != null) {
                            String timeArr = stringMap.get(id + "");
                            String[] split = timeArr.split(",");
                            for (int i = 0; i < split.length; i++) {
                                String attendtime = split[i];
                                if (DateUtil.valueCompTime(s, attendtime) >= 0) {//第一段考勤是否有考勤
                                    if (DateUtil.valueCompTime(starttimeOne, attendtime) >= 0) {
                                        e = 1;//"进班正常"
                                    }
                                    if (DateUtil.valueCompTime(s, attendtime) > 0) {//"进班迟到"
                                        if (e == 0) {
                                            b = 1;
                                        }
                                    }
                                }

                                if (DateUtil.valueCompTime(s, attendtime) <= 0 && DateUtil.valueCompTime(s1, attendtime) >= 0) {
                                    if (DateUtil.valueCompTime(endtimeOne, attendtime) >= 0) {//"离班早退"
                                        if (f == 0) {
                                            d = 1;
                                        }
                                    }
                                    if (DateUtil.valueCompTime(endtimeOne, attendtime) < 0) {//"离班正常"
                                        if (d == 0) {
                                            f = 1;
                                        }
                                    }
                                }

                                //第二段进班
                                if (DateUtil.valueCompTime(starttimeTwo, attendtime) >= 0 && DateUtil.valueCompTime(s1, attendtime) <= 0) {
                                    E = 1;//"进班正常"
                                } else {
                                    if (DateUtil.valueCompTime(starttimeTwo, attendtime) < 0 && DateUtil.valueCompTime(s3, attendtime) > 0) {//"进班迟到"
                                        if (E == 0) {
                                            B = 1;
                                        }
                                    }
                                }

                                //第二段离班
                                if (DateUtil.valueCompTime(endtimeTwo, attendtime) >= 0 && DateUtil.valueCompTime(s3, attendtime) <= 0) {//"离班早退"
                                    D = 1;
                                } else {
                                    if (DateUtil.valueCompTime(endtimeTwo, attendtime) < 0) {//"离班正常
                                        if (D == 0) {
                                            F = 1;
                                        }
                                    }
                                }
                            }
                            if (e == 0 && b == 0 && DateUtil.valueCompTime(gettime, s) > 0) {
                                a = 1;//"进班缺卡"
                            }
                            if (d == 0 && f == 0 && DateUtil.valueCompTime(gettime, s1) > 0) {
                                c = 1;//"离班缺卡"
                            }

                            if (E == 0 && B == 0 && DateUtil.valueCompTime(gettime, s3) > 0) {
                                A = 1;//"进班缺卡"
                            }
                            attendString = attendString(a, b, c, d, e, f, A, B, C, D, E, F);
                        }
                    }
                    list.add(attendString);
                }
            }
            List<String> attendList = new ArrayList<>();
            attendList.add(Integer.parseInt(stringObjectMap.get("zccount").toString()) + zc + e + E + f + F + "");
            attendList.add(stringObjectMap.get("qqcount").toString());
            attendList.add(Integer.parseInt(stringObjectMap.get("qkcount").toString()) + qk + a + A + c + C + "");
            attendList.add(Integer.parseInt(stringObjectMap.get("zdcount").toString()) + cd + b + B + "");
            attendList.add(Integer.parseInt(stringObjectMap.get("ztcount").toString()) + zt + d + D + "");
            attendList.addAll(list);
            stringObjectMap.put("attendlist", attendList);
        }

        listMap.put("weeklist", weekList);
        listMap.put("attendlist", maps);
        long endTime = System.currentTimeMillis(); //获取结束时间
        logger.info("考勤查询耗时： " + Double.valueOf(endTime - startTime) / 1000);
        return listMap;
    }


    @Override
    public void attendString() {
        String schoolId = "1";

        String gettime = DateUtil.addDays(DateUtil.gettime(), -1);//昨天时间

        int weeksInt = DateUtil.getWeeksInt(gettime);

        String sql = "SELECT id,IF(shift_id!=0,shift_id,(SELECT shift_id FROM attend_group_shift WHERE attend_group_id=attend_group.id AND sort=? ) ) shift_id FROM attend_group WHERE school_id=?";

        List<Map<String, Object>> list = attendJdbc.queryListMap(sql, weeksInt, schoolId);//获取所有考勤组

        String delSql = "delete from class_attendlist  WHERE   attend_group_id=?  AND   DATE(attendtime)= DATE_SUB(CURDATE(),INTERVAL 1 DAY) ";

        String delTwoSql = "delete from class_attendlist  WHERE   attend_group_id=?  AND attendtype is null AND  DATE(attendtime)= DATE_SUB(CURDATE(),INTERVAL 1 DAY) ";

        //休息 缺勤
        String addSql = "INSERT INTO class_attendlist(userid,attend_group_id,shift_id,attendtype,school_id,attendtime,sort,opertime) " +
                "SELECT userid,attend_group_id,?,?,?,DATE_FORMAT(DATE_SUB(NOW(),INTERVAL 1 DAY),'%Y-%m-%d'),0,DATE_FORMAT(DATE_SUB(NOW(),INTERVAL 1 DAY),'%Y-%m-%d') FROM attend_group_user WHERE attend_group_id=? ";

        //进班缺卡
        String addTwoSql = "INSERT INTO class_attendlist(userid,attend_group_id,shift_id,attendtype,school_id,attendtime,sort,opertime) " +
                "SELECT a.userid,a.attend_group_id,?,?,?,?,?,DATE_FORMAT(DATE_SUB(NOW(),INTERVAL 1 DAY),'%Y-%m-%d')  FROM attend_group_user a LEFT JOIN class_attendlist l " +
                "ON ( a.attend_group_id=l.attend_group_id AND a.userid=l.userid AND l.attendtime  BETWEEN ? AND ? ) WHERE a.attend_group_id=? AND l.id IS  NULL  GROUP BY a.userid ";

        //缺勤
        String qqSql = "SELECT GROUP_CONCAT(a.userid) string FROM attend_group_user a LEFT JOIN class_attendlist l ON ( a.attend_group_id=l.attend_group_id AND a.userid=l.userid AND l.attendtime  BETWEEN ? AND ? ) WHERE a.attend_group_id=? AND l.id IS  NULL ";


        String sqlShift = "SELECT  `type`, `starttime_one`, `endtime_one`, `starttime_two`, `endtime_two` FROM attend_shift WHERE id=?";

        //String sqlAttendList = "SELECT  a.userid,GROUP_CONCAT(l.attendtime ORDER BY l.attendtime) time,GROUP_CONCAT(l.id ORDER BY l.attendtime) id FROM attend_group_user a LEFT JOIN class_attendlist l ON ( a.attend_group_id=l.attend_group_id AND a.userid=l.userid AND    DATE(l.attendtime)= DATE_SUB(CURDATE(),INTERVAL 1 DAY) ) WHERE a.attend_group_id=?   GROUP BY a.userid  ";

        String updateSql = "UPDATE class_attendlist SET attendtype=?,shift_id=?,sort=? WHERE id IN (SELECT id FROM (SELECT MIN(l.id) id  FROM attend_group_user a LEFT JOIN class_attendlist l  " +
                "ON ( a.attend_group_id=l.attend_group_id AND a.userid=l.userid AND l.attendtime  BETWEEN ? AND ?  ) WHERE a.attend_group_id=?  AND l.id IS NOT NULL GROUP BY a.userid) t )";

        String updateTwoSql = "UPDATE class_attendlist SET attendtype=?,shift_id=?,sort=? WHERE id IN (SELECT id FROM (SELECT a.userid,MAX(l.id) id,GROUP_CONCAT(attendtype) attendtype  FROM attend_group_user a LEFT JOIN class_attendlist l  " +
                " ON ( a.attend_group_id=l.attend_group_id AND a.userid=l.userid AND l.attendtime> ? AND l.attendtime<? ) WHERE a.attend_group_id=? AND l.id IS NOT NULL  GROUP BY a.userid) t WHERE attendtype IS NULL ) ";


        // String userSql = "SELECT t.id string FROM attend_group_user u,student t WHERE  u.userid=t.id AND u.attend_group_id=?";

        String updateGroupSql = "UPDATE attend_group SET shift_id=0 WHERE id=?";

        if (list != null && list.size() > 0) {
            for (Map<String, Object> map : list) {//处理所有考勤组
                Object id = map.get("id");//考勤组id
                String shift_id = map.get("shift_id").toString();
                if ("-1".equals(shift_id) || "0".equals(shift_id)) {//考勤为休息
                    attendJdbc.updateByParameter(delSql, id);
                    attendJdbc.updateByParameter(addSql, 0, 7, schoolId, id);
                } else {//按班次时间处理当前的考勤数据
                    //List<String> userList = attendJdbc.queryListString(userSql, new Object[]{id});
                    Map<String, Object> timeMap = null;
                    try {
                        timeMap = attendJdbc.queryMap(sqlShift, shift_id);
                    } catch (Exception e) {
                        logger.info("executeInternal2.0-->erorr={}", e);
                    }
                    int type = (int) timeMap.get("type");//考勤类型:0 1天1次、1 1天2次
                    String starttimeOne = DateUtil.AddTime(gettime, timeMap.get("starttime_one") + "");
                    String endtimeOne = DateUtil.AddTime(gettime, timeMap.get("endtime_one") + "");
                    String starttimeTwo = DateUtil.AddTime(gettime, timeMap.get("starttime_two") + "");
                    String endtimeTwo = DateUtil.AddTime(gettime, timeMap.get("endtime_two") + "");

                    //考勤类型: 0请假 1进班正常 2进班迟到 3进班缺卡  4离班正常 5离班早退  6离班缺卡 7休息 8缺勤
                    if (type == 0) {
                        String time = "";
                        if (!StringUtils.isEmpty(endtimeOne) && !StringUtils.isEmpty(starttimeTwo)) {//设置了中间休息时段  取中间时间 区分进班迟到 和 离班早退
                            long l = DateUtil.getcompTime(starttimeTwo, endtimeOne);
                            time = DateUtil.addtimeMinutes(endtimeOne, (int) l / 2);
                        } else {//未设置了中间休息时段  取中间时间 区分进班迟到 和 离班早退
                            long l = DateUtil.getcompTime(endtimeTwo, starttimeOne);
                            time = DateUtil.addtimeMinutes(starttimeOne, (int) l / 2);
                        }
                        String userString = attendJdbc.queryString(qqSql, gettime, DateUtil.gettime(), id);

                        attendJdbc.updateByParameter(updateSql, 1, shift_id, 0, gettime, starttimeOne, id);//进班正常
                        //判断是 进班迟到
                        attendJdbc.updateByParameter(updateTwoSql, 2, shift_id, 0, gettime, time, id);
                        attendJdbc.updateByParameter(addTwoSql, shift_id, 3, schoolId, starttimeOne, 0, gettime, time, id);//进班缺卡


                        attendJdbc.updateByParameter(updateSql, 5, shift_id, 1, time, endtimeTwo, id);//离班早退
                        //判断是 离班正常
                        attendJdbc.updateByParameter(updateTwoSql, 4, shift_id, 1, time, DateUtil.gettime(), id);
                        attendJdbc.updateByParameter(addTwoSql, shift_id, 6, schoolId, endtimeTwo, 1, time, DateUtil.gettime(), id);//进班缺卡


                        if (!StringUtils.isEmpty(userString)) {//缺勤
                            String qqAddSql = "INSERT INTO class_attendlist(userid,attend_group_id,shift_id,attendtype,school_id,attendtime,sort,opertime) " +
                                    "   SELECT a.id,?,?,8,?,DATE_FORMAT(DATE_SUB(NOW(),INTERVAL 1 DAY),'%Y-%m-%d'),0,DATE_FORMAT(DATE_SUB(NOW(),INTERVAL 1 DAY),'%Y-%m-%d')  FROM student  a WHERE a.id in (" + userString + ")";
                            attendJdbc.updateByParameter(qqAddSql, id, shift_id, schoolId);
                            String delAttendSql = "DELETE FROM  class_attendlist WHERE attend_group_id=?   AND userid IN  (" + userString + ") AND (attendtype=3 or attendtype=6)";
                            attendJdbc.updateByParameter(delAttendSql, id);
                        }
                        attendJdbc.updateByParameter(delTwoSql, id);//删除null的
                        attendJdbc.updateByParameter(updateGroupSql, id);//修改考勤组
                    } else {
                        //求第一段考勤的中间时间  用来区分 进班迟到和离班早退
                        long l = DateUtil.getcompTime(endtimeOne, starttimeOne);
                        String s = DateUtil.addtimeMinutes(starttimeOne, (int) l / 2);
                        //求第一段考勤的结束时间和第二段开始时间的中间时间  用来区分 离班正常和第二段的进班正常
                        long l1 = DateUtil.getcompTime(starttimeTwo, endtimeOne);
                        String s1 = DateUtil.addtimeMinutes(endtimeOne, (int) l1 / 2);
                        //求第二段考勤的中间时间  用来区分 进班迟到和离班早退
                        long l2 = DateUtil.getcompTime(endtimeTwo, starttimeTwo);
                        String s3 = DateUtil.addtimeMinutes(starttimeTwo, (int) l2 / 2);

                        String userString = attendJdbc.queryString(qqSql, gettime, DateUtil.gettime(), id);

                        attendJdbc.updateByParameter(updateSql, 1, shift_id, 0, gettime, starttimeOne, id);//进班正常
                        //判断是 进班迟到
                        attendJdbc.updateByParameter(updateTwoSql, 2, shift_id, 0, gettime, s, id);
                        attendJdbc.updateByParameter(addTwoSql, shift_id, 3, schoolId, starttimeOne, 0, gettime, s, id);//进班缺卡


                        attendJdbc.updateByParameter(updateSql, 5, shift_id, 1, s, endtimeOne, id);//离班早退
                        //判断是 离班正常
                        attendJdbc.updateByParameter(updateTwoSql, 4, shift_id, 1, s, s1, id);
                        attendJdbc.updateByParameter(addTwoSql, shift_id, 6, schoolId, endtimeOne, 1, s, s1, id);//离班缺卡


                        //考勤类型: 0请假 1进班正常 2进班迟到 3进班缺卡  4离班正常 5离班早退  6离班缺卡 7休息 8缺勤
                        //第二段
                        attendJdbc.updateByParameter(updateSql, 1, shift_id, 2, s1, starttimeTwo, id);//进班正常
                        //判断是 进班迟到
                        attendJdbc.updateByParameter(updateTwoSql, 2, shift_id, 2, s1, s3, id);
                        attendJdbc.updateByParameter(addTwoSql, shift_id, 3, schoolId, starttimeTwo, 2, s1, s3, id);//进班缺卡


                        //第二段
                        attendJdbc.updateByParameter(updateSql, 5, shift_id, 3, s3, endtimeTwo, id);//离班早退
                        //判断是 离班正常
                        attendJdbc.updateByParameter(updateTwoSql, 4, shift_id, 3, s3, DateUtil.gettime(), id);
                        attendJdbc.updateByParameter(addTwoSql, shift_id, 6, schoolId, endtimeTwo, 3, s3, DateUtil.gettime(), id);//离班缺卡

                        if (!StringUtils.isEmpty(userString)) {//缺勤
                            String qqAddSql = "INSERT INTO class_attendlist(userid,attend_group_id,shift_id,attendtype,school_id,attendtime,sort,opertime) " +
                                    "   SELECT a.id,?,?,8,?,DATE_FORMAT(DATE_SUB(NOW(),INTERVAL 1 DAY),'%Y-%m-%d'),0,DATE_FORMAT(DATE_SUB(NOW(),INTERVAL 1 DAY),'%Y-%m-%d')  FROM student  a WHERE a.id in (" + userString + ")";
                            attendJdbc.updateByParameter(qqAddSql, id, shift_id, schoolId);
                            String delAttendSql = "DELETE FROM  class_attendlist WHERE attend_group_id=?   AND userid IN  (" + userString + ") AND (attendtype=3 or attendtype=6)";
                            attendJdbc.updateByParameter(delAttendSql, id);
                        }

                        attendJdbc.updateByParameter(delTwoSql, id);//删除null的
                        attendJdbc.updateByParameter(updateGroupSql, id);//修改考勤组
                    }
                }
            }
        }
    }

    public String attendString(int a, int b, int c, int d, int e, int f, int A, int B, int C, int D, int E, int F) {
        logger.info("attendString-->,a={},b={},c={},d={},e={},f={},A={},B={},C={},D={},E={},F={}", a, b, c, d, e, f, A, B, C, D, E, F);
        StringBuilder builder = new StringBuilder();
        if (e == 1) {
            builder.append("进班正常 ");
        }
        if (a == 1) {
            builder.append("进班缺卡 ");
        }
        if (b == 1) {
            builder.append("进班迟到 ");
        }
        if (f == 1) {
            builder.append("离班正常");
        }
        if (c == 1) {
            builder.append("离班缺卡");
        }
        if (d == 1) {
            builder.append("离班早退");
        }

        if (A == 1) {
            builder.append(" 进班缺卡");
        }
        if (B == 1) {
            builder.append(" 进班迟到");
        }
        if (E == 1) {
            builder.append(" 进班正常");
        }
        if (C == 1) {
            builder.append(" 离班缺卡");
        }
        if (D == 1) {
            builder.append(" 离班早退");
        }
        if (F == 1) {
            builder.append(" 离班正常");
        }
        return builder.toString();
    }

    private int saveAttendGroup(String name, long shift_id, String school_id, Integer attend_groupid) {
        String sql = "update `attend_group` set `name`=?, `shift_id`=?, `school_id`=?, `opertime`=now() where id=?";
        return attendJdbc.updateByParameter(sql, name, shift_id, school_id, attend_groupid);
    }

    private int saveAttendGroupShift(String shift_id, Integer attend_groupid) {
        String sql = "insert into `attend_group_shift` (`shift_id`, `attend_group_id`, `opertime`, `sort`) values(?,?,now(),?)";
        return attendJdbc.updateAttendGroupShift(sql, shift_id, attend_groupid);
    }
}
